package com.blog.generator.utils;

import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 通过设定的txt文件（excel设定）转化为创建表的sql语句
 * - 处理华海报表
 * @author ly
 * create at 2021/8/19 - 16:01
 **/
public class ReadText2CreateTableSql {

    public static void main(String[] args) {
        Map<String, Object> map = read2Sql("D:\\learn\\workspace\\idea\\blog3-generator\\src\\main\\resources\\excel.txt");

        StringBuilder sql = new StringBuilder();

        // todo 添加表名和描述
//        String tableName = "HUAHAI_REPORT_1068_CCX_LIST";
//        String tableDesc = "财产险报案清单";

        String tableName = "HUAHAI_REPORT_1069_NX_LIST";
        String tableDesc = "农险报案清单";




        sql.append("DROP TABLE IF EXISTS `"+tableName+"`;\n");
        sql.append("CREATE TABLE `"+tableName+"` (\n");
        sql.append("`ID` VARCHAR ( 36 ) CHARACTER  SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'ID',\n");

        map.entrySet().forEach(item ->{
            String key = item.getKey();
            Object value = item.getValue();
            sql.append("`"+key+"` VARCHAR ( 50 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '"+value+"',\n");
        });

        sql.append("PRIMARY KEY ( `ID` ) USING BTREE \n" +
                ") ENGINE = INNODB CHARACTER \n" +
                "SET = utf8 COLLATE = utf8_general_ci COMMENT = '"+tableDesc+"' ROW_FORMAT = Dynamic;");

        System.out.println(sql.toString());
    }

    private static Map<String,Object> read2Sql(String filePath){
        Map<String,Object> map = new LinkedHashMap<>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(filePath));

            String i;
            while ((i = reader.readLine()) != null){
                if(!StringUtils.isBlank(i)){
                    String[] arr = i.split("\t");
                    map.put(arr[1],arr[0]);
                }
            }

        }catch (Exception e){

        }finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;

    }


}
